import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/stock_materialarrival_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/stock_materialarrival.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/stock_materialarrival/stock_materialarrival_dialog.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:quiver/strings.dart';

class StockMaterialarrivalList extends StatefulWidget {
  StockMaterialarrivalList({Key? key}) : super(key: key);

  @override
  _StockMaterialarrivalListState createState() =>
      _StockMaterialarrivalListState();
}

class _StockMaterialarrivalListState extends State<StockMaterialarrivalList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  StockMaterialarrival stockMaterialarrival = StockMaterialarrival();
  List<StockMaterialarrival> selectedList = [];
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      // _query();
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 180,
            label: '采购订单号',
            value: stockMaterialarrival.purchaseordercode,
            onSaved: (v) {
              stockMaterialarrival.purchaseordercode = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('采购订单号')),
        DataColumn(label: Text('行号')),
        DataColumn(label: Text('物料编码（零件号）')),
        DataColumn(label: Text('物料描述（零件描述）')),
        DataColumn(label: Text('供应商编码')),
        DataColumn(label: Text('供应商名称')),
        DataColumn(label: Text('单位')),
        DataColumn(label: Text('到货数量')),
        DataColumn(label: Text('收货方式')),
        DataColumn(label: Text('到货日期')),
        DataColumn(label: Text('备注')),
      ],
      getCells: (m) {
        StockMaterialarrival stockMaterialarrival =
            StockMaterialarrival.fromMap(m);
        return [
          DataCell(Text(stockMaterialarrival.purchaseordercode ?? '--')),
          DataCell(Text(stockMaterialarrival.linenumber ?? '--')),
          DataCell(Text(stockMaterialarrival.materialcode ?? '--')),
          DataCell(Text(stockMaterialarrival.materialname ?? '--')),
          DataCell(Text(stockMaterialarrival.suppliercode ?? '--')),
          DataCell(Text(stockMaterialarrival.suppliername ?? '--')),
          DataCell(Text(stockMaterialarrival.purchaseunit ?? '--')),
          DataCell(Text(stockMaterialarrival.arrivalquantity ?? '--')),
          DataCell(Text(stockMaterialarrival.deliveredfashion ?? '--')),
          DataCell(Text(stockMaterialarrival.arriveddate ?? '--')),
          DataCell(Text(stockMaterialarrival.remark ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    stockMaterialarrival = StockMaterialarrival();
    formKey.currentState!.reset();
    tableKey.currentState?.pageTo(0);
    tableKey.currentState!.loadData(PageModel());
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    // 默认无数据
    if (isBlank(stockMaterialarrival.purchaseordercode)) {
      tableKey.currentState?.pageTo(0);
      tableKey.currentState!.loadData(PageModel());
      CryUtils.message("请输入采购订单号");
      return;
    }
    ResponseBodyApi responseBodyApi = await StockMaterialarrivalOdooApi.page(
        data: {
          "page": page,
          "domainList": stockMaterialarrival.toDomainList()
        });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: StockMaterialarrivalDialog(),
      ),
    ).then((v) {
      if (v != null) {
        stockMaterialarrival = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<StockMaterialarrival>((e) => StockMaterialarrival.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
      ],
    );
  }
}
